//
//  AddressViewController.swift
//  DollarBuy
//
//  Created by 郑东喜 on 2016/11/8.
//  Copyright © 2016年 郑东喜. All rights reserved.
//  收获地址界面

import UIKit

class AddressViewController: MeBaseViewController,UIPickerViewDelegate,UIPickerViewDataSource {
    
    
    /**
     用户动态标识ID
     add:添加；upd:更新；del:删除；def:默认；list:列表
     0:实体地址；1：虚拟地址   （ac为list时不需要）
     省份
     城市
     区、县
     详细地址
     收货人姓名
     收货人手机
     收货人QQ
     默认地址（1：是；0：否）

     */
    
    //用户名
    @IBOutlet weak var tfName: UITextField!
    
    //联系方式
    @IBOutlet weak var tfNum: UITextField!
    
    //省份
    @IBOutlet weak var province: UITextField!
    
    //城市
    @IBOutlet weak var city: UITextField!
    
    //地区
    @IBOutlet weak var cityLocal: UITextField!
    
    //详细地址
    @IBOutlet weak var detailAddress: UITextField!
    
    //默认地址
    @IBOutlet weak var defaultAddress: UITextField!

    
    //qq
    @IBOutlet weak var qq: UITextField!

    let addressArray = ["交易明细","中奖纪录","收获地址","分享有礼"]
    let cityArray = ["收获地址","分享有礼"]
    var pickerView = UIPickerView()
    
    //收货地址请求参数"ac"，根据获取到的收货地址列表的数组个数进行判断
    var ac = ""
    

    override func viewDidLoad() {
        super.viewDidLoad()

            // Do any additional setup after loading the view.
        self.title = "我的收货地址"
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension AddressViewController {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if localSave.object(forKey: userToken) as? String != nil {
            
            let token = localSave.object(forKey: userToken) as! String
            
            let param = ["token":token,
                         "ac":"list",
                         ] as [String : Any]
            
            print(param)
        
            //发送请求
            postWithPath(path: addressUrl, paras: param, success: { (response) in
                
                print("\((#file as NSString).lastPathComponent):(\(#line))")
//                let dic = response as! NSDictionary
                
                guard let dic = response as? NSDictionary else {
                    return
                }
                
                print(dic)
                //提取提示语
                let alertmsg = dic["resultmsg"] as! String
                
                
                if alertmsg == "请求成功" {
                    
                    
                    //测试文件
                    let url = URL(fileURLWithPath: "/Users/zhengdongxi/Desktop/资料ios/abc.plist", isDirectory: true)
                    dic.write(to: url, atomically: true)
                    
                    
                    guard let list = ((dic["data"] as! NSDictionary)["list"] as? NSArray) else {
                        return
                    }
                    
                    
                    //list数组为空，就返回
                    if list.count == 0 {
                        //1.为空则为保存按钮传递增添参数就是ac="add"否则ac=upd
                        self.ac = "add"
                        
                        return
                    }
                        //1.为空则为保存按钮传递增添参数就是ac="add"否则ac=upd
                        self.ac = "upd"
                    
                    //提取数据填到对应的文本
                    let dataSource = (list)[0] as! NSDictionary

                    
                    print(dataSource)
                    
                    //qq信息
                    self.qq.text = dataSource["qq"] as? String
                    //收货人
                    self.tfName.text = dataSource["shrname"] as? String
                    
                    //联系方式
                    self.tfNum.text = dataSource["shrphone"] as? String

                    //省份
                    self.province.text = dataSource["province"] as? String
                    
                    //城市
                    self.city.text = dataSource["city"] as? String
                    
                    //地区
                    self.cityLocal.text = dataSource["area"] as? String
                    
                    //详细地址
                    self.detailAddress.text = dataSource["addrs"] as? String
                } else {
                    return
                } 
                

                print("\((#file as NSString).lastPathComponent):(\(#line))")
                
            }) { (error) in
                print(error.localizedDescription)
            }
        
        } else {
            return
        }

    }
}

// MARK:- 设置按钮事件
extension AddressViewController {
    
    //保存信息
    @IBAction func saveInfo(_ sender: UIButton) {
        print("\((#file as NSString).lastPathComponent):(\(#line)):(\("保存信息")))")
        infoUpdate()

    }
}

// MARK:- datePickerView
extension AddressViewController {
    func setUpData() -> Void {
        pickerView = UIPickerView(frame: CGRect(x: 0, y: UIScreen.main.bounds.height - 130, width: UIScreen.main.bounds.width, height: 130))
        pickerView.backgroundColor = UIColor.blue
        view.addSubview(pickerView)
        
        self.pickerView.delegate = self
        self.pickerView.dataSource = self

    }
}

// MARK:- 信息提交
extension AddressViewController {
    func infoUpdate() -> Void {
        
        if self.tfName.text?.characters.count == 0 {
            MBManager.showBriefAlert("收货人姓名不能为空")
            
        } else if self.tfNum.text?.characters.count == 0 {
            MBManager.showBriefAlert("联系方式不能为空")
            
        } else if self.province.text?.characters.count == 0 {
            MBManager.showBriefAlert("省份不能为空")
            
        } else if self.city.text?.characters.count == 0 {
            MBManager.showBriefAlert("城市不能为空")
            
        } else if self.cityLocal.text?.characters.count == 0 {
            MBManager.showBriefAlert("地区不能为空")
            
        } else if self.detailAddress.text?.characters.count == 0 {
            MBManager.showBriefAlert("详细地址不能为空")
            
        } else if localSave.object(forKey: userToken) as? String != nil {
            let token = localSave.object(forKey: userToken) as! String
            
            let param = ["token":token,
                         "ac":ac,
//                         "ac":"upd",
                         "ty" : "0",
                         "province" : self.province.text!,
                         "city" : self.city.text!,
                         "area" : self.cityLocal.text!,
                         "addrs" : self.detailAddress.text!,
                         "shrname" : self.tfName.text!,
                         "shrphone" : self.tfNum.text!,
                         "qq" : self.qq.text!,
                    ] as [String : Any]
            
            print(param)
            
            postWithPath(path: addressUrl, paras: param, success: { (response) in
                
                
                guard let dic = response as? NSDictionary else {
                    return
                }
                
                print(dic)
                
                
                
                //修改地址错误时的提示语
                guard let changeWrongMsg = dic["msg"] as? String else {
                    
                    
                    //提取提示语
                    guard let alertmsg = dic["resultmsg"] as? String else {
                        return
                    }
                    
                    print(dic)
                    
                    if alertmsg == "添加地址成功" {
                        
                        
                        MBManager.showBriefAlert(addressAddSuccess)
                    } else if alertmsg == "修改地址成功" {
                        
                        print("修改地址成功")
                        MBManager.showBriefAlert(addresUpdateSuccess)
                    }

                    
                    
                    return
                }
                
                print(changeWrongMsg)
                
                if changeWrongMsg == "尝试修改地址不存在" {
                    MBManager.showBriefAlert(changeAddressFail)
                }

                
                
            }) { (error) in
                print(error.localizedDescription)
            }
   
            
        } else {
            MBManager.showBriefAlert("登陆后才可查看收获信息")
            return
        }

    }
}

extension AddressViewController {
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return self.addressArray.count
    }
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        //        print(cityDataSource.count)
        //        return cityDataSource.count
        return 1
    }
    
    //设置选择框各选项的内容，继承于UIPickerViewDelegate协议
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int,
                    forComponent component: Int) -> String? {
        
        
        if(component == 0)
        {
            return self.addressArray[row]
        }
        else
        {
            return self.cityArray[row]
        }
        
    }
    
    //监听选择的行列
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        print("\((#file as NSString).lastPathComponent):(\(#line)):(\("选择的行")))")
        print(row)
        
        print("\((#file as NSString).lastPathComponent):(\(#line)):(\("选择的列")))")
        print(component)
    }
}
